<template>
  <div class="setting-page">
    <!-- 使用通用页头组件 -->
    <PageHeader 
      title="个人设置"
      :showLeftButton="false"
      :showRightButton="true"
      rightText="保存"    
      @right-button-click="saveSettings"
    />
    
    <div class="content">
      <PullRefresh @refresh="onRefresh">
        <!-- 使用Element Plus的折叠面板 -->
        <el-collapse v-model="activeNames" class="setting-collapse">
          <!-- 用户信息设置 -->
          <el-collapse-item title="用户信息" name="userInfo">
            <!-- 头像设置 -->
            <div class="avatar-setting">
              <!-- 头像预览 -->
              <div v-if="settings._avatarPreview" class="avatar-preview-container">
                <img :src="settings._avatarPreview" class="avatar-preview" />
              </div>
              
              <!-- 头像裁剪组件 -->
              <AvatarCrop 
                v-else
                :initial-avatar="settings._avatarPreview || ''"
                @avatar-selected="handleAvatarSelected"
              />
            </div>
            
            <!-- 用户名设置 -->
            <div class="setting-item">
              <div class="setting-label">用户名</div>
              <div class="setting-value">
                <el-input 
                  v-model="settings.username" 
                  placeholder="请输入用户名"
                  class="mobile-input"
                ></el-input>
              </div>
            </div>
          </el-collapse-item>
          
          <!-- 外观设置 -->
          <el-collapse-item title="外观设置" name="appearance">
            <!-- 主题颜色设置 -->
            <div class="setting-item">
              <div class="setting-label">主题颜色</div>
              <div class="setting-value">
                <div class="color-preview" :style="{ backgroundColor: settings.themeColor }" @click="showColorPicker = true"></div>
                <span class="color-value">{{ settings.themeColor }}</span>
              </div>
            </div>
            
            <!-- 显示模式设置 -->
            <div class="setting-item">
              <div class="setting-label">显示模式</div>
              <div class="setting-value">
                <div class="radio-group">
                  <div 
                    v-for="mode in displayModes" 
                    :key="mode.value"
                    class="radio-item" 
                    :class="{ active: settings.displayMode === mode.value }"
                    @click="settings.displayMode = mode.value"
                  >
                    <div class="radio-label">{{ mode.label }}</div>
                    <div class="radio-icon" :class="{ checked: settings.displayMode === mode.value }"></div>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-item>
          
          <!-- 数据管理 -->
          <el-collapse-item title="数据管理" name="data">
            <div class="action-buttons">
              <button class="action-button export-button" @click="exportData">
                <span class="button-icon">📤</span>
                导出数据
              </button>
              <button class="action-button clear-button" @click="confirmClearData">
                <span class="button-icon">🗑️</span>
                清空数据
              </button>
            </div>
          </el-collapse-item>
          
          <!-- 关于 -->
          <el-collapse-item title="关于" name="about">
            <div class="about-content">
              <div class="app-icon">📝</div>
              <h3 class="app-name">人生事件记录</h3>
              <p class="app-version">v1.0.0</p>
              <p class="app-description">记录生命中的每一个重要时刻</p>
            </div>
          </el-collapse-item>
        </el-collapse>
        
        <!-- 恢复默认按钮 -->
        <button class="reset-button" @click="confirmResetSettings">恢复默认设置</button>
      </PullRefresh>
    </div>
    
    <!-- 清空数据确认弹窗 -->
    <div v-if="showClearConfirm" class="confirm-dialog">
      <div class="confirm-dialog-content">
        <h3>确认清空</h3>
        <p>确定要清空所有数据吗？此操作不可恢复！</p>
        <div class="confirm-buttons">
          <button class="dialog-button cancel-button" @click="showClearConfirm = false">取消</button>
          <button class="dialog-button confirm-button" @click="clearData">确定</button>
        </div>
      </div>
    </div>
    
    <!-- 重置设置确认弹窗 -->
    <div v-if="showResetConfirm" class="confirm-dialog">
      <div class="confirm-dialog-content">
        <h3>确认重置</h3>
        <p>确定要恢复默认设置吗？</p>
        <div class="confirm-buttons">
          <button class="dialog-button cancel-button" @click="showResetConfirm = false">取消</button>
          <button class="dialog-button confirm-button" @click="resetSettings">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PageHeader from '../components/PageHeader.vue'
import PullRefresh from '../components/PullRefresh.vue'
import AvatarCrop from '../components/AvatarCrop.vue'
import { ElMessage, ElCollapse, ElCollapseItem } from 'element-plus'
import { uploadFile, getImageDataUrl, saveUserSettings, getUserSettings, getUserInfo, updateUserInfo, DEFAULT_USER_ID } from '../services/api.js'

export default {
  name: 'SettingPage',
  components: {
    PageHeader,
    PullRefresh,
    AvatarCrop,
    ElCollapse,
    ElCollapseItem
  },
  data() {
    return {
      settings: {
        username: '用户名',
        avatar: '',
        _avatarPreview: '',
        themeColor: '#409eff',
        displayMode: 'light'
      },
      activeNames: ['userInfo'], // 默认展开用户信息面板
      showClearConfirm: false,
      showResetConfirm: false,
      showColorPicker: false,
      displayModes: [
        { label: '浅色模式', value: 'light' },
        { label: '深色模式', value: 'dark' },
        { label: '跟随系统', value: 'auto' }
      ]
    }
  },
  mounted() {
    // 页面加载时从数据库获取用户设置
    this.loadUserSettings()
  },
  
  methods: {
    // 处理从AvatarCrop组件接收到的裁剪后的头像
    async handleAvatarSelected(croppedAvatarData) {
      try {
        this.isLoading = true;
        
        // 先显示本地预览
        this.settings._avatarPreview = croppedAvatarData.previewUrl;
        
        // 上传裁剪后的头像文件
        const uploadedFile = await uploadFile(croppedAvatarData.file);
        
        if (uploadedFile && uploadedFile.url) {
          // 保存头像URL到设置中
          this.settings.avatarUrl = uploadedFile.url;
          // 标记为已修改
          this.settings._avatarChanged = true;
          ElMessage.success('头像上传成功');
        } else {
          ElMessage.error('上传头像失败，请重试');
          // 如果上传失败，恢复之前的预览
          this.settings._avatarPreview = this.settings.avatarUrl || '';
        }
      } catch (error) {
        ElMessage.error('处理头像时出错');
        console.error('处理头像错误:', error);
        // 恢复之前的预览
        this.settings._avatarPreview = this.settings.avatarUrl || '';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 从localStorage加载用户设置
    async loadUserSettings() {
      try {
        // 1. 从localStorage获取用户基本信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr)
          if (userInfo.username) {
            this.settings.username = userInfo.username
          }
          if (userInfo.avatar) {
            this.settings.avatar = userInfo.avatar
            // 加载头像预览
            await this.loadAvatarPreview()
          }
          console.log('用户基本信息已从localStorage加载:', userInfo)
        }
        
        // 2. 从localStorage获取用户设置
        const userSettingsStr = localStorage.getItem('userSettings')
        if (userSettingsStr) {
          const savedSettings = JSON.parse(userSettingsStr)
          if (savedSettings && typeof savedSettings === 'object') {
            // 只合并非用户信息的设置，避免覆盖已加载的用户信息
            const { username, avatar, ...otherSettings } = savedSettings
            this.settings = { ...this.settings, ...otherSettings }
            console.log('用户设置已从localStorage加载:', otherSettings)
          }
        }
      } catch (error) {
        console.error('从localStorage加载用户数据失败:', error)
        // 如果localStorage加载失败，尝试直接从数据库加载作为降级方案
        await this.loadSettingsFromDatabase()
      }
    },
    
    // 从数据库加载用户设置（降级方案）
    async loadSettingsFromDatabase() {
      try {
        // 1. 先获取用户基本信息（用户名和头像）
        const userInfo = await getUserInfo()
        if (userInfo && typeof userInfo === 'object') {
          if (userInfo.username) {
            this.settings.username = userInfo.username
          }
          if (userInfo.avatar) {
            this.settings.avatar = userInfo.avatar
            // 加载头像预览
            await this.loadAvatarPreview()
          }
          // 更新localStorage
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          console.log('用户基本信息已从数据库加载并更新到localStorage:', userInfo)
        }
        
        // 2. 再获取用户设置
        const savedSettings = await getUserSettings(DEFAULT_USER_ID)
        if (savedSettings && typeof savedSettings === 'object') {
          // 只合并非用户信息的设置，避免覆盖已加载的用户信息
          const { username, avatar, ...otherSettings } = savedSettings
          this.settings = { ...this.settings, ...otherSettings }
          // 更新localStorage
          localStorage.setItem('userSettings', JSON.stringify(savedSettings))
          console.log('用户设置已从数据库加载并更新到localStorage:', otherSettings)
        }
      } catch (error) {
        console.error('加载用户数据失败:', error)
      }
    },
    // 触发头像上传
    triggerAvatarUpload() {
      this.$refs.avatarInput.click()
    },
    
    // 处理头像上传
    async handleAvatarChange(e) {
      const file = e.target.files[0]
      if (file) {
        try {
          // 先显示本地预览
          const reader = new FileReader()
          reader.onload = async e => {
            // 先显示本地预览，提升用户体验
            this.settings._avatarPreview = e.target.result
            
            try {
              // 上传文件到后端并获取URL
              const fileUrl = await uploadFile(file, DEFAULT_USER_ID)
              // 保存文件路径而不是base64
              this.settings.avatar = fileUrl
              console.log('头像已上传，文件路径:', fileUrl)
            } catch (error) {
              console.error('头像上传失败:', error)
              // 即使上传失败，也保留本地预览
            }
          }
          reader.readAsDataURL(file)
        } catch (error) {
          console.error('头像处理失败:', error)
        }
      }
      // 清空input，以便可以重复选择相同的文件
      this.$refs.avatarInput.value = ''
    },
    
    // 保存设置
    async saveSettings() {
      try {
        // 1. 先保存用户基本信息到t_user表
        await updateUserInfo(this.settings.username, this.settings.avatar)
        console.log('用户信息已保存到t_user表')
        
        // 2. 然后保存其他设置到t_user_settings表
        // 从settings中排除username和avatar，因为它们已经保存在t_user表中
        const { username, avatar, ...settingsToSave } = this.settings
        await saveUserSettings(settingsToSave, DEFAULT_USER_ID)
        
        // 3. 更新localStorage中的数据，保持一致性
        // 更新用户基本信息
        const userInfo = {
          username: this.settings.username,
          avatar: this.settings.avatar
        }
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        console.log('用户基本信息已更新到localStorage:', userInfo)
        
        // 更新用户设置
        localStorage.setItem('userSettings', JSON.stringify(settingsToSave))
        console.log('用户设置已更新到localStorage:', settingsToSave)
        
        this.$message.success('设置保存成功！')
      } catch (error) {
        console.error('保存设置失败:', error)
        this.$message.error('保存设置失败，请重试')
      }
    },
    
    // 显示重置确认
    confirmResetSettings() {
      this.showResetConfirm = true
    },
    
    // 重置设置
    resetSettings() {
      this.settings = {
        username: '用户名',
        avatar: '',
        _avatarPreview: '',
        themeColor: '#409eff',
        displayMode: 'light'
      }
      
      // 更新localStorage中的数据
      const defaultUserInfo = {
        username: '用户名',
        avatar: ''
      }
      
      const defaultSettings = {
        themeColor: '#409eff',
        displayMode: 'light'
      }
      
      localStorage.setItem('userInfo', JSON.stringify(defaultUserInfo))
      localStorage.setItem('userSettings', JSON.stringify(defaultSettings))
      console.log('已重置localStorage中的用户信息和设置')
      
      this.$message.success('已恢复默认设置！')
      this.showResetConfirm = false
    },
    
    // 导出数据
    exportData() {
      this.$message.info('导出功能开发中...')
    },
    
    // 显示清空确认
    confirmClearData() {
      this.showClearConfirm = true
    },
    
    // 清空数据
    clearData() {
      this.$message.success('数据已清空！')
      this.showClearConfirm = false
    },
    
    // 处理左侧按钮点击
    handleLeftButton(defaultAction) {
      // 使用默认行为（返回上一页）
      defaultAction()
    },
    
    // 下拉刷新回调
    async onRefresh() {
      // 重新加载用户设置
      await this.loadUserSettings()
      this.$message.success('设置已刷新')
    },
    
    // 加载头像预览
    async loadAvatarPreview() {
      if (this.settings.avatar) {
        try {
          // 获取图片数据并设置为预览
          this.settings._avatarPreview = await getImageDataUrl(this.settings.avatar)
        } catch (error) {
          console.error('加载头像预览失败:', error)
        }
      }
    },
    
    // 获取图片URL用于显示
    getImageUrl(imagePath) {
      // 这里可以返回完整的图片URL或使用占位符
      // 实际显示会通过loadAvatarPreview加载真实的预览
      return '/placeholder.png'
    }
  }
}
</script>

<style scoped>
.setting-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative;
  padding-bottom: 60px;
}

/* 顶部导航栏 - 移动端样式 */
.page-header {
  background-color: #fff;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 1rem;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-button {
  height: 36px;
  padding: 0 12px;
  border: none;
  background: none;
  color: #409eff;
  font-size: 16px;
  cursor: pointer;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 60px;
}

.left-button {
  justify-content: flex-start;
}

.right-button {
  justify-content: flex-end;
}

.header-button.primary {
  background-color: #409eff;
  color: #fff;
}

.back-icon {
  margin-right: 4px;
  font-size: 18px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.content {
  width: 100%;
  margin: 0;
  flex: 1;
  height: calc(100vh - 50px); /* 假设页头高度为50px */
  overflow: hidden;
}

/* 折叠面板样式 */
.setting-collapse {
  background-color: transparent;
  border: none;
}

.setting-collapse .el-collapse-item__header {
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 600;
  font-size: 16px;
  padding: 1rem;
  height: auto;
  line-height: 1.5;
}

:deep(.el-collapse-item__title) {
  padding: 0 1rem !important;
}

.setting-collapse .el-collapse-item__wrap {
  background-color: #fff;
  padding: 1rem;
}

:deep(.el-collapse-item__content) {
  padding: 1rem;
}

/* 头像设置 */
.avatar-setting {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 1.5rem;
}

/* 头像预览样式 */
.avatar-preview-container {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #4CAF50;
  margin: 0 auto 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-container {
  position: relative;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f0f0;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 3px solid #f0f0f0;
}

.avatar-icon {
  font-size: 32px;
}

.avatar-edit {
  position: absolute;
  right: -5px;
  bottom: 0;
  width: 32px;
  height: 32px;
  background-color: #409eff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 3px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.edit-icon {
  font-size: 16px;
  color: #fff;
}

/* 设置项 */
.setting-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #f0f0f0;
}

.setting-item:last-of-type {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.setting-label {
  font-size: 15px;
  color: #333;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.setting-value {
  display: flex;
  align-items: center;
}

/* 移动端输入框 */
.mobile-input {
  width: 100%;
  font-size: 16px;
}

.mobile-input input {
  font-size: 16px !important; /* 防止iOS缩放 */
}

/* 颜色选择器 */
.color-preview {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  border: 1px solid #ddd;
  margin-right: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.color-value {
  font-size: 14px;
  color: #666;
}

/* 单选按钮组 */
.radio-group {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.radio-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  border-radius: 8px;
  background-color: #f5f5f5;
  margin-bottom: 0.5rem;
  transition: all 0.2s ease;
}

.radio-item.active {
  background-color: #e6f7ff;
  border: 1px solid #409eff;
}

.radio-label {
  font-size: 15px;
  color: #333;
}

.radio-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

.radio-icon.checked::after {
  content: '';
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #409eff;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.action-button {
  flex: 1;
  height: 48px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  gap: 8px;
  transition: all 0.2s ease;
}

.export-button {
  background-color: #e6f7ff;
  color: #409eff;
  border: 1px solid #409eff;
}

.clear-button {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

.button-icon {
  font-size: 18px;
}

/* 关于部分 */
.about-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1rem 0;
}

.app-icon {
  font-size: 48px;
  margin-bottom: 1rem;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 0.5rem 0;
}

.app-version {
  font-size: 14px;
  color: #999;
  margin: 0 0 0.5rem 0;
}

.app-description {
  font-size: 14px;
  color: #666;
  margin: 0;
  text-align: center;
  padding: 0 1rem;
}

/* 重置按钮 */
.reset-button {
  width: calc(100% - 2rem);
  margin: 1.5rem auto;
  height: 48px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fff;
  color: #666;
  font-size: 16px;
  cursor: pointer;
}

/* 确认弹窗 */
.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.confirm-dialog-content {
  background-color: white;
  border-radius: 12px;
  padding: 1.5rem;
  width: 85%;
  max-width: 360px;
}

.confirm-dialog-content h3 {
  margin: 0 0 1rem 0;
  font-size: 18px;
  color: #333;
  text-align: center;
}

.confirm-dialog-content p {
  margin: 0 0 1.5rem 0;
  font-size: 16px;
  color: #666;
  text-align: center;
  line-height: 1.5;
}

.confirm-buttons {
  display: flex;
  gap: 1rem;
}

.dialog-button {
  flex: 1;
  height: 44px;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  cursor: pointer;
}

.cancel-button {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-button {
  background-color: #f56c6c;
  color: white;
}

/* 隐藏滚动条但保留功能 */
.content::-webkit-scrollbar {
  display: none;
}

.content {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
</style>